<?php
// +----------------------------------------------------------------------
// | 字典管理
// +----------------------------------------------------------------------
namespace app\admin\controller;

use dc\controller\AdminBaseController;
use dragon\Support\Dictionary;
use dragon\Support\TMSSync;
use think\Db;
use think\Validate;

/**
 * Class DictionaryController
 * @package app\admin\controller
 * @adminMenuRoot(
 *     'name'   => '字典管理',
 *     'action' => 'default',
 *     'parent' => 'admin/Dictionary/default',
 *     'display'=> true,
 *     'Dictionary'  => 10000,
 *     'icon'   => '',
 *     'remark' => '字典管理'
 * )
 */
class DictionaryController extends AdminBaseController
{
    protected $perpage = 40;
    /************ [ 字典管理 Start ] *************/

    /**
     * 字典列表
     * @adminMenu(
     *     'name'   => '字典列表',
     *     'parent' => 'default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'Dictionary'  => 10000,
     *     'icon'   => '',
     *     'remark' => '字典列表',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        /**搜索条件**/
        $dict_type = $this->request->param('dict_type', '', 'trim');
        $keyword = $this->request->param('keyword');

        $map = [];
        $dict_type and $map['dict_type'] = $dict_type;
        $keyword and $map['key|value'] = ['like', "%$keyword%"];

        $list = Db::name('dictionary')->where($map)->order('dict_type asc, list_order asc')->paginate($this->perpage);

        // 获取分页显示
        $page = $list->render();

        $this->assign('dict_types', Dictionary::get('dict_type'));
        $this->assign("page", $page);
        $this->assign("list", $list);
        return $this->fetch();
    }

    /**
     * 字典添加
     * @adminMenu(
     *     'name'   => '字典添加',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'Dictionary'  => 10000,
     *     'icon'   => '',
     *     'remark' => '管理员添加',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        $this->assign('dict_types', Dictionary::get('dict_type'));
        return $this->fetch('dictionary/form');
    }

    /**
     * 字典编辑
     * @adminMenu(
     *     'name'   => '字典编辑',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'Dictionary'  => 10000,
     *     'icon'   => '',
     *     'remark' => '字典编辑',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $dictionary = Db::name('dictionary')->find($this->request->param('id'));
        $this->assign("dictionary", $dictionary);
        $this->assign('dict_types', Dictionary::get('dict_type'));
        return $this->fetch('dictionary/form');
    }

    /**
     * 字典保存
     */
    public function save()
    {
        $id = $this->request->param('id', 0, 'intval');
        $post = $this->request->post();

        $validate = new Validate([
            'dict_type' => 'require',
            'key' => 'require|unique:dictionary,dict_type^key,'.$id,
            'value' => 'require',
        ],[
            'dict_type.require' => '请选择类型',
            'key.require' => 'key 不可为空',
            'key.unique' => 'key 已存在，不可重复添加',
            'value.require' => 'value 不可为空',
        ]);
        if (!$validate->check($post)) {
            $this->error($validate->getError());
        }

        try {
            Db::startTrans();
            if($id) {
                Db::name('dictionary')->where(['id' => $id])->update($post);
            } else {
                Db::name('dictionary')->insertGetId($post);
            }
            Dictionary::clear();
            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }


        $this->success('保存成功');
    }

    /**
     * 字典删除
     * @adminMenu(
     *     'name'   => '字典删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'Dictionary'  => 10000,
     *     'icon'   => '',
     *     'remark' => '字典删除',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id == 1) {
            $this->error("最高管理员不能删除！");
        }

        if (Db::name('user')->delete($id) !== false) {
            Db::name("RoleUser")->where(["user_id" => $id])->delete();
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    /**
     * 字典排序
     * @adminMenu(
     *     'name'   => '字典排序',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '字典排序',
     *     'param'  => ''
     * )
     */
    public function listOrder()
    {
        $model = new \dragon\Entity\Dictionary();
        $status       = parent::listOrders($model);
        // 清除缓存
        Dictionary::clear();
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }


}